package com.work08.common;

import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author 绛河
 * @date 2023/4/19
 * @apiNote
 */
@Component
public class Upload {
    public void saveFile(MultipartFile file, String subDirectory) throws FileNotFoundException {
        String staticPath = ResourceUtils.getURL("classpath:").getPath() + "static";
        String fileName = file.getOriginalFilename();
        String urlPath = subDirectory + File.separator + fileName;
        String savePath = staticPath + File.separator + urlPath;
        String visitPath ="static/" + urlPath;
        System.out.println("图片访问uri：" + visitPath);
        File saveFile = new File(savePath);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
